package com.eppear.jpfm.framework.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ZJF
 * @Description 日期工具类 *
 */
public class DateUtil {
	private static Logger log = LoggerFactory.getLogger(DateUtil.class);
	/**
	 * 默认日期格式
	 */
	public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

	public static final String[] WEEK_DAYS = { "日", "一", "二", "三", "四", "五", "六" };
	
	/**
	 * @Description 字符串转换成日期. <如果转换格式为空，则利用默认格式进行转换操作>
	 * 
	 * @param str
	 *            字符串
	 * @param format
	 *            日期格式
	 * @return 日期
	 */
	public static Date str2Date(String str, String format) {
		if (null == str || "".equals(str)) {
			return null;
		}
		// 如果没有指定字符串转换的格式，则用默认格式进行转换
		if (null == format || "".equals(format)) {
			format = DEFAULT_FORMAT;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(str);
			return date;
		} catch (ParseException e) {
			log.error("", e);
		}

		return null;
	}

	/**
	 * 日期转换成字符串
	 * 
	 * @param date
	 *            日期
	 * @param format
	 *            日期格式
	 * @return 字符串
	 */
	public static String date2Str(Date date, String format) {
		if (null == date) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	/**
	 * 
	 * @return 获得当前系统时间
	 */
	public static Timestamp getCutTime() {
		return new Timestamp(System.currentTimeMillis());
	}

	/**
     * 获取当前时间 yyyyMMddHHmmss
     * 
     * @return String
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getNowDateTimeString() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 获取现在时间
	 * 
	 * @return 返回短时间字符串格式yyyy-MM-dd
	 */
	public static String getNowDateString() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 把一个字符串时间转换为毫秒值 如 2014-12-12 12:12:12 转换为 1406086513619
	 * 
	 * @param strDate
	 * @return
	 */
	public static long str2DateTime(String strDate) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			pe.getStackTrace();
		}
		return date.getTime();
	}

	/**
	 * 计算两个日期之间相差的月数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getMonths(Date date1, Date date2) {
		int iMonth = 0;
		int flag = 0;
		try {
			Calendar objCalendarDate1 = Calendar.getInstance();
			objCalendarDate1.setTime(date1);
			Calendar objCalendarDate2 = Calendar.getInstance();
			objCalendarDate2.setTime(date2);
			if (objCalendarDate2.equals(objCalendarDate1))
				return 0;
			if (objCalendarDate1.after(objCalendarDate2)) {
				Calendar temp = objCalendarDate1;
				objCalendarDate1 = objCalendarDate2;
				objCalendarDate2 = temp;
			}
			if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1.get(Calendar.DAY_OF_MONTH))
				flag = 1;

			if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1.get(Calendar.YEAR))
				iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1.get(Calendar.YEAR)) * 12
						+ objCalendarDate2.get(Calendar.MONTH) - flag) - objCalendarDate1.get(Calendar.MONTH);
			else
				iMonth = objCalendarDate2.get(Calendar.MONTH) - objCalendarDate1.get(Calendar.MONTH) - flag;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return iMonth;
	}

	/**
	 * 获取当前星期（中国, 如：星期日,星期一,星期二）
	 */
	public static String cnWeek() {
		Calendar c = GregorianCalendar.getInstance();
		c.setFirstDayOfWeek(Calendar.SUNDAY);
		String[] s = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		return s[c.get(Calendar.DAY_OF_WEEK) - 1];
	}

	/**
	 * 得到一个日期是周几
	 */
	public static String getWeekCS(Date date) {

		Calendar c = GregorianCalendar.getInstance();
		c.setTime(date);
		c.setFirstDayOfWeek(Calendar.SUNDAY);
		String[] s = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" };
		return s[c.get(Calendar.DAY_OF_WEEK) - 1];
	}

	/**
	 * 得到一个日期是周几
	 */
	public static String getWeekInNum(Date date) {

		Calendar c = GregorianCalendar.getInstance();
		c.setTime(date);
		int weekDayNum = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (weekDayNum == 0) {
			weekDayNum = 7;
		}
		return String.valueOf(weekDayNum);
	}

	/**
	 * 取传入时间的小时值
	 * 
	 * @param endDate
	 * @return
	 */
	public static String makeHour(Date endDate) {
		String hour = "";
		if (endDate != null) {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String after = format.format(endDate);
			hour = after.substring(11, 13);
		}
		return hour;
	}

	public static String makeMini(Date endDate) {
		String mini = "";
		if (endDate != null) {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String after = format.format(endDate);
			mini = after.substring(14, 16);
		}
		return mini;
	}

	/**
	 * 得到当前时间的 小时和分（hh:mm）
	 * 
	 * @param date
	 * @return
	 */
	public static String getHourAndMinute(Date date) {
		String hour = makeHour(date);
		String minute = makeMini(date);

		return hour + ":" + minute;
	}

	@SuppressWarnings("unchecked")
	public static List getTomorrowList() {
		List<String> dateList = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String tomorrow = sdf.format(calendar.getTime());
		dateList.add(tomorrow);
		for (int i = 0; i < 6; i++) {
			calendar.set(6, calendar.get(6) + 1);
			tomorrow = sdf.format(calendar.getTime());
			dateList.add(tomorrow);
		}

		return dateList;
	}

	@SuppressWarnings("unchecked")
	public static List getWeekDateList(String date) throws ParseException {
		List<String> dateList = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
		Date dateVar = ymd.parse(date);
		calendar.setTime(dateVar);
		dateList.add(date);
		for (int i = 1; i <= 6; i++) {
			calendar.set(6, calendar.get(6) + 1);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String tomorrow = sdf.format(calendar.getTime());
			dateList.add(tomorrow);
		}
		return dateList;
	}

	/**
	 * 返回日期date 前推beforHour小时后的 日期
	 * 
	 * @param date
	 * @param beforHour
	 * @return
	 */
	public static Date getBeforHourDate(Date date, int beforHour) {

		if (date != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			c.set(Calendar.HOUR, c.get(Calendar.HOUR) - beforHour);

			return c.getTime();
		}
		return null;
	}

	/**
	 * 取给定日期的前一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getLastDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 1);
		return calendar.getTime();
	}

	/**
	 * 返回两时间的相差天数
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static int getDayNumBetween2Date(Date d1, Date d2) {

		if (isEqualsInYMD(d1, d2)) {
			return 0;
		}

		long l = d2.getTime() - d1.getTime();
		int day = (int) (l / (24 * 60 * 60 * 1000));
		if (day < 0) {
			day = (-day);
		}

		int m = (int) (l % (24 * 60 * 60 * 1000));
		Calendar c = Calendar.getInstance();
		if (d1.compareTo(d2) <= 0) {
			c.setTime(d1);
			c.add(Calendar.MILLISECOND, m);
			if (isEqualsInYMD(d1, c.getTime())) {
				return day;
			} else {
				return day + 1;
			}
		} else {
			c.setTime(d2);
			c.add(Calendar.MILLISECOND, m);
			if (isEqualsInYMD(d2, c.getTime())) {
				return day;
			} else {
				return day + 1;
			}
		}

	}

	/**
	 * 两个时间是否是 同年 同月 同日 如果是，则返回true，否则返回false
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static boolean isEqualsInYMD(Date d1, Date d2) {

		Calendar c = Calendar.getInstance();

		c.setTime(d1);
		int year1 = c.get(Calendar.YEAR);
		int dayOfYear1 = c.get(Calendar.DAY_OF_YEAR);

		c.setTime(d2);
		int year2 = c.get(Calendar.YEAR);
		int dayOfYear2 = c.get(Calendar.DAY_OF_YEAR);

		if (year1 != year2) {
			return false;
		}
		if (dayOfYear1 != dayOfYear2) {
			return false;
		}

		return true;
	}

	/**
	 * 获得当前月的前 i 个月
	 * 
	 * @param i
	 *            (henrry) return 月的数组
	 */
	public static String[] getMonthArr(int i) {
		String arr[] = new String[i];
		Calendar c = Calendar.getInstance();
		int temp = 0;
		int tempp = 0;
		int year = 0;
		int month = 0;
		int m = i - 1;
		for (int j = 0; j < m; j++) {
			if (i > 12) {
				temp = (i - 1) / 12;
				tempp = (i - 1) % 12;
				year = c.get(Calendar.YEAR) - temp;
				month = c.get(Calendar.MONTH) - tempp + 1;
				if (month < 10 && month > 0) {
					arr[j] = year + "-0" + month;
				} else if (month < 0) {
					month = 12 + month;
					if (month < 10) {
						arr[j] = (year - 1) + "-0" + month;
					} else {
						arr[j] = (year - 1) + "-" + month;
					}
				} else if (month == 0) {
					arr[j] = (year - 1) + "-" + 12;
				} else {
					arr[j] = year + "-" + month;
				}
			} else {
				year = c.get(Calendar.YEAR);
				month = c.get(Calendar.MONTH) - i + 2;
				if (month < 10 && month > 0) {
					arr[j] = year + "-0" + month;
				} else if (month < 0) {
					month = 12 + month;
					if (month < 10) {
						arr[j] = (year - 1) + "-0" + month;
					} else {
						arr[j] = (year - 1) + "-" + month;
					}
				} else if (month == 0) {
					arr[j] = (year - 1) + "-" + 12;
				} else {
					arr[j] = year + "-" + month;
				}
			}
			i--;
		}
		int monthNow = c.get(Calendar.MONTH);
		if (monthNow > 8) {
			arr[m] = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1);
		} else {
			arr[m] = c.get(Calendar.YEAR) + "-0" + (c.get(Calendar.MONTH) + 1);
		}
		return arr;
	}

	/**
	 * 得到两个时间之间的差距，根据type可返回分别以天，时，分为单位的整数
	 * 
	 * @param d1
	 * @param d2
	 * @param type
	 * @return
	 */
	public static int getBetweenDateGap(Date d1, Date d2, String type) {
		long time1 = d1.getTime();
		long time2 = d2.getTime();
		long m = (time1 - time2) / 1000;
		int nDay = (int) m / (24 * 60 * 60);
		int nHour = (int) (m - nDay * 24 * 60 * 60) / (60 * 60);
		int nMinute = (int) (m - nDay * 24 * 60 * 60 - nHour * 60 * 60) / 60;
		int mSecond = (int) (m - nDay * 24 * 60 * 60 - nHour * 60 * 60);
		if ("day".equals(type)) {
			return nDay;
		} else if ("minute".equals(type)) {
			return nMinute;
		} else if ("hour".equals(type)) {
			return nHour;
		} else if ("second".equals(type)) {
			return mSecond;
		}
		return nMinute;
	}

	/**
	 * 通过月份计算季度 
	 * 
	 * @param month
	 *           
	 * @return
	 */
	public static int getQuarter(int month) {
		if (month < 1 || month > 12) {
			throw new IllegalArgumentException("month is invalid.");
		}
		return (month - 1) / 3 + 1;
	}
	@Test
	public void  test() {
		System.out.println(this.str2Date("2017-10-01","yyyy-MM-dd"));
		System.out.println(this.date2Str(this.getCutTime(), "yyyy-MM-dd HH:MM:ss"));
		log.debug("测试信息===>getNowDateTimeString{}",getNowDateTimeString());
		log.debug("测试信息===>cnWeek{}",this.cnWeek());
		log.debug("测试信息===>getCurrTime{}",this.getCurrTime());
	}
}
